<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>计算属性</title>
	<link rel="stylesheet" href="../style.css">
	<script src="../vue.js"></script>
</head>
<body>
	<p class="title">计算属性</p>
	<div id="app">
		<p>original  message:{{message}}</p>
		<p>reversed  message:{{reversedMessage}}</p>
		<p>reversed  message:{{reversedMessage1()}}</p>
		<p> {{now()}}</p>
	</div>
	<script>
		var app = new Vue({
			el:'#app',
			data:{
				message:'Hello',
			},
			computed:{
				reversedMessage:function (argument) {
					return this.message.split('').reverse().join('');
				}
			},

			// 没有缓存
			methods:{
				reversedMessage1:function (argument) {
					return this.message.split('').reverse().join('');
				},
				now:function(){
					return  Date();
				}
			}
		})
	</script>
	
	<p class="subtitle">计算属性vs Watched Property</p>
	<div id="app2">
		<input type="text" v-model="firstName" v-on:blur="show"><br/>
		<input type="text" v-model="lastName">
		<p>{{fullName}}</p>

	</div>
	<script>
		var app2=new Vue({
			el:'#app2',
			data:{
				firstName:'Foo',
				lastName:'Bar',
				fullName:'Foo Bar'
			},
			watch:{
				firstName:function(val){
					this.fullName=val+' '+this.lastName;
				},
				lastName:function(val){
					this.fullName=this.firstName+' '+val;
				}
			},
			methods:{
				show:function(){
					// alert('a');
				}
			},
			// computed:{
			// 	fullName:function(){
			// 		return this.firstName+' '+this.lastName;
			// 	}
			// }
		})
		// $watch 两个不一样 与56行相比
		
		// app2.$watch('firstName',function(firstName){
		// 	console.log(firstName);
		// })
	</script>

	<p class="title">观察watcher</p>
	<div id="app3">
		<p>Ask a yes/no question: <input type="text" v-model="question"></p>
		<p>{{answer}}</p>
	</div>
	<script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
	<script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>
	<script>
		var app3=new Vue({
			el:'#app3',
			data:{
				question:'',
				answer:'I cannot give you an answer until you ask a question!',
			},
			watch:{
				question:function(newQuestion){
					this.answer='Waiting for you to stop typing...'
					this.getAnswer()
				}
			},
			methods:{
				getAnswer:_.debounce(
					function(){
						var vm=this
						if(this.question.indexOf('?') === -1) {
							vm.answer = 'Questions usually contain a question mark. ;-)'
          		return
						}
						vm.answer='Thinking....'
						axios.get('https://yesno.wtf/api')
							.then(function (response) {
	            	vm.answer = _.capitalize(response.data.answer)
	         		})
	         		.catch(function (error) {
	            	vm.answer = 'Error! Could not reach the API. ' + error
	          	})
						},
					500
				)
			}
		})
	</script>
</body>
</html>